<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\shop\controller;

use api\index\controller\CommonController;
use app\admin\controller\ShopGoodsController;
use app\admin\model\ChangeCoinModel;
use app\admin\model\FavoriteModel;
use app\admin\model\InfoSetModel;
use app\admin\model\MemberModel;
use app\admin\model\ShopGoodsModel;
use app\admin\model\ShopGoodsRelationModel;
use app\admin\model\ShopOrderModel;
use cmf\controller\RestBaseController;
use app\admin\model\CommonModel;
use think\Db;

//商城
class GoodsController extends RestBaseController
{
    protected $noNeedLogin = ['finishTimeOrder'];

    //商品分类
    public function goodsCategory(){
        if($this->request->isGet()){
            $res = CommonController::selectData('shop_category','id,shop_name','sort desc');
            $this->success('成功',$res);
        }else{
            $this->error('请求方式错误');
        }
    }

    //商品列表
    public function goodsList(){
        if($this->request->isGet()){
            $shop_id = $this->request->get('shop_id');
            $page = $this->request->get('page');//分页页码
            $rule = config('verify.goods_list');
            $this->checkValidate(['shop_id'=>$shop_id,'page'=>$page],$rule);

            $res = CommonController::selectWherePageData('shop_goods',['shop_id'=>$shop_id],$page,'id,title,thumbnail,min_price,min_stock','sort desc');
            //查询登录人收藏的记录
            $member_id = $this->getUserId();
            $where = [
                'member_id' => $member_id,
                'type' => FavoriteModel::COLLECTION,
                'relation_type' => FavoriteModel::GOODS_TYPE
            ];
            $res_collection = CommonController::selectWhereData('favorite',$where,'id,relation_id');
            foreach($res as &$value){
                $value['thumbnail'] = CommonController::absolutionUrl($value['thumbnail']);
                //是否收藏
//                $value['is_collection'] = FavoriteModel::NO;//否
//                foreach($res_collection as $c_value){
//                    if($value['id'] == $c_value['relation_id']){
//                        $value['is_collection'] = FavoriteModel::YES;//是
//                        break;
//                    }
//                }
            }
            $total_page = CommonController::totalWherePage('shop_goods',['shop_id'=>$shop_id]);
            $this->success('成功',['data'=>$res,'last_page'=>$total_page]);
        }else{
            $this->error('请求方式错误');
        }
    }

    //商品详情
    public function goodsDetail(){
        if($this->request->isGet()){
            $goods_id = $this->request->get('goods_id');//商品id
            $rule = config('verify.goods_detail');
            $this->checkValidate(['goods_id'=>$goods_id],$rule);

            $res = CommonController::findWhereData('shop_goods',['id'=>$goods_id],'id,title,shop_id,thumbnail,images,content,is_shelf,is_specs,min_price,min_stock,sales');
            if($res){
                $res['thumbnail'] = CommonController::absolutionUrl($res['thumbnail']);
                $images = explode(',',$res['images']);
                $arr_images = [];
                foreach($images as $img_value){
                    array_push($arr_images,CommonController::absolutionUrl($img_value));
                }
                $res['images'] = $arr_images;
                $commonModel = new CommonModel();
                $res['content'] = $commonModel->getPostContentAttr($res['content']);
                //规格组等级
                $count = CommonController::totalWhere('specs',['shop_id'=>$res['shop_id']]);
                //规格层级
                if($res['is_specs'] == ShopGoodsModel::SPECS_NO){
                    $res['level'] = ShopGoodsModel::SPECS_NO;//没有规格组
                }else{
                    $res['level'] = $count;
                }
                $res['specs_attr'] = CommonController::getSpecsAttr($res,ShopGoodsModel::LEVEL_FIRST);
                unset($res['is_specs']);
            }
            $this->success('成功',$res);
        }else{
            $this->error('请求方式错误');
        }
    }

    //获取商品层级一级二级三级规格组
    public function levelSpecs(){
        if($this->request->isGet()){
            $goods_id = $this->request->get('goods_id');//商品id
            $attr_id = $this->request->get('attr_id');//二级属性id
            $parent_attr_id = $this->request->get('parent_attr_id');//查询三级需要 一级属性id
            $level = $this->request->get('level');//层级，传递0,1,2
            $rule = config('verify.level_specs');
            $this->checkValidate(['goods_id'=>$goods_id,'attr_id'=>$attr_id,'level'=>$level],$rule);

            $res = CommonController::findWhereData('shop_goods',['id'=>$goods_id],'id,shop_id');
            if(!$res){
                $this->error('商品不存在');
            }

            if($level == ShopGoodsModel::LEVEL_THIRD){
                if(!isset($parent_attr_id) && empty($parent_attr_id)){
                    $this->error('一级属性id不能为空');
                }
                $arr = CommonController::getSpecsAttr($res,$level,$attr_id,$parent_attr_id);
            }else{
                $arr = CommonController::getSpecsAttr($res,$level,$attr_id);
            }
            $this->success('成功',$arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    //查询一级二级三级价格，库存
    public function getPriceStock(){
        if($this->request->isGet()){
            $goods_id = $this->request->get('goods_id');//商品id
            $parent_attr_id = $this->request->get('parent_attr_id');//一级属性id
            $second_attr_id = $this->request->get('second_attr_id');//二级属性id
            $third_attr_id = $this->request->get('third_attr_id');//三级属性id
            $level = $this->request->get('level');//等级，传递1,2,3
            $rule = config('verify.goods_detail');
            $this->checkValidate(['goods_id'=>$goods_id],$rule);
            if(!isset($level) && empty($level)){
                $this->error('等级不能为空');
            }
            $data['parent_attr_id'] = $parent_attr_id;
            $data['second_attr_id'] = $second_attr_id;
            $data['third_attr_id'] = $third_attr_id;
            $this->checkSpecs($level,$data);

            $res = CommonController::findWhereData('shop_goods',['id'=>$goods_id],'id,shop_id');
            if(!$res){
                $this->error('商品不存在');
            }

            //查询库存价格
            $price_stock_arr = CommonController::getSpecsPriceStock($res,$data);
            $this->success('成功',$price_stock_arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    //检测规格属性层级
    private function checkSpecs($level,$data){
        if($level == ShopGoodsModel::FIRST){
            //一级
            if(!isset($data['parent_attr_id']) || empty($data['parent_attr_id'])){
                $this->error('一级属性id不能为空');
            }
        }else if($level == ShopGoodsModel::SECOND){
            //二级
            if(!isset($data['parent_attr_id']) || empty($data['parent_attr_id'])){
                $this->error('一级属性id不能为空');
            }
            if(!isset($data['second_attr_id']) || empty($data['second_attr_id'])){
                $this->error('二级属性id不能为空');
            }
        }else{
            //三级
            if(!isset($data['parent_attr_id']) || empty($data['parent_attr_id'])){
                $this->error('一级属性id不能为空');
            }
            if(!isset($data['second_attr_id']) || empty($data['second_attr_id'])){
                $this->error('二级属性id不能为空');
            }
            if(!isset($data['third_attr_id']) || empty($data['third_attr_id'])){
                $this->error('三级属性id不能为空');
            }
        }
    }

    //商品下单
    public function submitOrder(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $rule = config('verify.submit_order');
            $this->checkValidate($data,$rule);

            $res = CommonController::findWhereData('shop_goods',['id'=>$data['goods_id']],'id,title,shop_id,thumbnail,is_specs,min_price,min_stock');
            $arr = [];
            if($res){
                $arr['id'] = $res['id'];
                $arr['title'] = $res['title'];
                $arr['num'] = $data['num'];
                $arr['thumbnail'] = CommonController::absolutionUrl($res['thumbnail']);
                //规格层级
                if($res['is_specs'] == ShopGoodsModel::SPECS_NO){
                    //没有规格组
                    $arr['goods_coin'] = $res['min_price'];
                    $arr['stock'] = $res['min_stock'];
                    $arr['total_coin'] = $res['min_price']*$data['num'];
                }else{
                    //规格组等级
                    $level = CommonController::totalWhere('specs',['shop_id'=>$res['shop_id']]);
                    $this->checkSpecs($level,$data);
                    //所选中规格属性名称逗号隔开
                    if(!isset($data['specs_attr']) || empty($data['specs_attr'])){
                        $this->error('选中规格属性名称不能为空');
                    }

                    //查询库存价格
                    $price_stock_arr = CommonController::getSpecsPriceStock($res,$data);
                    if(!$price_stock_arr){
                        $this->error('未查到该属性规格');
                    }

                    //选中规格组ids,names
                    if($level == ShopGoodsModel::FIRST){
                        //一级
                        $arr['parent_attr_id'] = $data['parent_attr_id'];
                    }else if($level == ShopGoodsModel::SECOND){
                        //二级
                        $arr['parent_attr_id'] = $data['parent_attr_id'];
                        $arr['second_attr_id'] = $data['second_attr_id'];
                    }else{
                        //三级
                        $arr['parent_attr_id'] = $data['parent_attr_id'];
                        $arr['second_attr_id'] = $data['second_attr_id'];
                        $arr['third_attr_id'] = $data['third_attr_id'];
                    }
                    $arr['specs_attr'] = $data['specs_attr'];
                    //库存价格
                    $arr['goods_coin'] = $price_stock_arr['goods_coin'];
                    $arr['stock'] = $price_stock_arr['goods_stock'];
                    $arr['total_coin'] = $arr['goods_coin']*$data['num'];
                }
            }
            $this->success('成功',$arr);
        }else{
            $this->error('请求方式错误');
        }
    }

    //确认订单
    public function confirmOrder(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $rule = config('verify.confirm_order');
            $this->checkValidate($data,$rule);

            $res = CommonController::findWhereData('shop_goods',['id'=>$data['goods_id']],'id,title,shop_id,is_specs,thumbnail,is_specs,min_price,min_stock');
            if(!$res){
                $this->error('未找到该商品');
            }

            $member = $this->user;
            //第三等级可以兑换商品
            if($member['level'] < MemberModel::THREE_LEVEL){
                $this->error('等级不够，无法兑换');
            }

            //规格层级
            if($res['is_specs'] == ShopGoodsModel::SPECS_NO){
                //没有规格组
                //判断库存
                if($res['min_stock'] < $data['num']){
                    $this->error('库存不足');
                }
                //判断购买人球币
                $goods_coin = $res['min_price'];
                $total_coin = $goods_coin*$data['num'];
                if($member['coin'] < $total_coin){
                    $this->error('球币不足，无法兑换');
                }
                $price_stock_id = $res['id'];
            }else{
                //规格组等级
                $level = CommonController::totalWhere('specs',['shop_id'=>$res['shop_id']]);
                $this->checkSpecs($level,$data);

                //所选中规格属性名称逗号隔开
                if(!isset($data['specs_attr']) || empty($data['specs_attr'])){
                    $this->error('选中规格属性名称不能为空');
                }

                //查询库存价格
                $price_stock_arr = CommonController::getSpecsPriceStock($res,$data);
                if(!$price_stock_arr){
                    $this->error('未查到该属性规格');
                }
                $price_stock_id = $price_stock_arr['goods_relation_id'];
                //判断库存
                if($price_stock_arr['goods_stock'] < $data['num']){
                    $this->error('该属性规格库存不足');
                }
                $goods_coin = $price_stock_arr['goods_coin'];
                $total_coin = $goods_coin*$data['num'];
                //判断购买人球币
                if($member['coin'] < $total_coin){
                    $this->error('球币不足，无法兑换');
                }

                if($level == ShopGoodsModel::FIRST){
                    //一级
                    $data['specs_attr_ids'] = $data['parent_attr_id'];
                }else if($level == ShopGoodsModel::SECOND){
                    //二级
                    $data['specs_attr_ids'] = $data['parent_attr_id'].','.$data['second_attr_id'];
                }else{
                    //三级
                    $data['specs_attr_ids'] = $data['parent_attr_id'].','.$data['second_attr_id'].','.$data['third_attr_id'];
                }
            }

            $data['shop_id'] = $res['shop_id'];
            $data['shop_goods_id'] = $res['id'];
            $data['title'] = $res['title'];
            $data['thumbnail'] = $res['thumbnail'];
            $data['member_id'] = $member['id'];
            $data['need_coin'] = $goods_coin;
            $data['need_count_coin'] = $total_coin;
            $data['shop_goods_id'] = $data['goods_id'];
            $data['shop_order_sn'] = CommonController::getOrderSn('LGQ');
            //创建成功订单
            Db::startTrans();
            $shopOrderModel = new ShopOrderModel();
            $arr = $shopOrderModel->allowField(true)->create($data);
            //减用户球币
            $memberModel = new MemberModel();
            $arr1 = $memberModel->where('id',$member['id'])->setDec('coin',$total_coin);
            //更新库存
            $goodsModel = new ShopGoodsModel();
            if($res['is_specs'] == ShopGoodsModel::SPECS_NO){
                $arr2 = $goodsModel->where('id',$price_stock_id)->setDec('min_stock',$data['num']);
            }else{
                $relationModel = new ShopGoodsRelationModel();
                $arr2 = $relationModel->where('id',$price_stock_id)->setDec('stock',$data['num']);
            }
            //增加销量
            $arr3 = $goodsModel->where('id',$data['goods_id'])->setInc('sales',$data['num']);
            //球币变动
            $member = MemberModel::get($member['id']);
            $arr4 = CommonController::changeCoin($member['id'],ChangeCoinModel::FOR_GOODS ,$res['id'],'兑换商品','-'.$total_coin, $member->coin);
            if($arr && $arr1 && $arr2 && $arr3 && $arr4){
                //更新用户球币
                Db::commit();
                $this->success('成功',['order_id'=>$arr->id]);
            }else{
                Db::rollback();
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    //我的商品订单
    public function myOrderList(){
        if($this->request->isGet()){
            $status = $this->request->get('status');//-1：全部，0：待发货，1：待收货，2：已完成
            $page = $this->request->get('page');//分页页码
            $rule = config('verify.my_order_list');
            $this->checkValidate(['status'=>$status,'page'=>$page],$rule);

            $where['member_id'] = $this->getUserId();
            if($status != -1){
                $where['status'] = $status;
            }
            $res = CommonController::selectWherePageData('shop_order',$where,$page,'id,shop_order_sn,status,thumbnail,title,specs_attr,need_coin,num,need_count_coin,remarks');
            foreach($res as &$value){
                $value['thumbnail'] = CommonController::absolutionUrl($value['thumbnail']);
            }
            $total_page = CommonController::totalWherePage('shop_order',$where);
            $this->success('成功',['data'=>$res,'last_page'=>$total_page]);
        }else{
            $this->error('请求方式错误');
        }
    }

    //商品订单详情
    public function myOrderDetail(){
        if($this->request->isGet()){
            $order_id = $this->request->get('order_id');
            $rule = config('verify.my_order_detail');
            $this->checkValidate(['order_id'=>$order_id],$rule);

            $member_id = $this->getUserId();
            $res = CommonController::findWhereData('shop_order',['id'=>$order_id,'member_id'=>$member_id],'*');
            if($res){
                $res['thumbnail'] = CommonController::absolutionUrl($res['thumbnail']);
                $res['deliver_time'] = !empty($res['deliver_time'])?date('Y-m-d H:i:s',$res['deliver_time']):'';
                $res['finish_time'] = !empty($res['finish_time'])?date('Y-m-d H:i:s',$res['finish_time']):'';
                $res['create_time'] = date('Y-m-d H:i:s',$res['create_time']);
                unset($res['update_time']);
            }
            $this->success('成功',$res);
        }else{
            $this->error('请求方式错误');
        }
    }

    //完成订单
    public function finishOrder(){
        if($this->request->isGet()){
            $order_id = $this->request->get('order_id');
            $rule = config('verify.my_order_detail');
            $this->checkValidate(['order_id'=>$order_id],$rule);

            $orderModel = new ShopOrderModel();
            $member_id = $this->getUserId();
            $res = $orderModel->where(['id'=>$order_id,'member_id'=>$member_id,'status'=>ShopOrderModel::RECEIPT])->update(['status'=>ShopOrderModel::FINISH,'finish_time'=>time()]);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    //删除订单
    public function deleteOrder(){
        if($this->request->isGet()){
            $order_id = $this->request->get('order_id');
            $rule = config('verify.my_order_detail');
            $this->checkValidate(['order_id'=>$order_id],$rule);

            $orderModel = new ShopOrderModel();
            $member_id = $this->getUserId();
            $res = $orderModel->where(['id'=>$order_id,'member_id'=>$member_id,'status'=>ShopOrderModel::FINISH])->delete();
            if($res){
                $this->success('删除成功');
            }else{
                $this->error('失败');
            }
        }
    }

    //定时完成订单
    public function finishTimeOrder(){
        if($this->request->isGet()){
            //查询待收货订单
            $res = CommonController::selectWhereData('shop_order',['status'=>ShopOrderModel::RECEIPT],'id,deliver_time');
            $arr = [];
            //五天用户没收或自动收货
            $time = time();
            foreach ($res as $value){
                $finish_time = $value['deliver_time'] + 86400*5;
                if($time < $finish_time){
                    array_push($arr,$value['id']);
                }
            }
            $orderModel = new ShopOrderModel();
            $orderModel->whereIn('id',$arr)->update(['status'=>ShopOrderModel::FINISH,'finish_time'=>time()]);
        }else{
            $this->error('请求方式错误');
        }
    }
}
